package cn.easyutil.easyproject.easySpringboot.handler;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.easyutil.easyproject.easySpringboot.context.Context;
import cn.easyutil.easyproject.easySpringboot.util.RequestPool;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import com.example.easyJavaUtil.JsonUtil;
import com.example.easyJavaUtil.LoggerUtil;
import com.example.easyJavaUtil.StringUtil;

/**
 * 请求过滤器
 * 
 * @author spc
 *
 */
@Configuration
public class ServletRequestAuthorition extends OncePerRequestFilter {

	public static ThreadLocal<Boolean> useResponse = new ThreadLocal<>();
	public static ThreadLocal<String> reqUri = new ThreadLocal<>();
	public static ThreadLocal<String> reqToken = new ThreadLocal<>();

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap());
		String requestUri = request.getRequestURI();
		String callNoStr = requestUri.substring(requestUri.lastIndexOf("/") + 1);
		reqUri.set(callNoStr);
		reqToken.set(RequestPool.getToken());
		LoggerUtil.info(this.getClass(), "----------------------------------");
		LoggerUtil.info(this.getClass(), "==> sessionId : " + RequestPool.get().getSession().getId());
		LoggerUtil.info(this.getClass(), "==> ip : " + getIpAddress());
		LoggerUtil.info(this.getClass(), "请求路径：" + requestUri);
		if(StringUtil.isNumber(callNoStr)){
			useResponse.set(true);
		}else{
			useResponse.set(false);
		}
		RequestPool.setSessionAttribute(Context.threadLocal_request_url, callNoStr);
		// 修改请求参数
		ServletRequestWrapper req = new ServletRequestWrapper(request, parameterMap);
		if (req.getParameterMap() != null && !req.getParameterMap().isEmpty()) {
			LoggerUtil.info(this.getClass(), "请求参数：" + JsonUtil.beanToJson(request.getParameterMap()));
		}
		// 调用对应的controller
		super.doFilter(req, response, filterChain);
	}

	// 获取客户端IP地址
	private String getIpAddress() {
		String ip = RequestPool.get().getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
			ip = RequestPool.get().getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = RequestPool.get().getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = RequestPool.get().getRemoteAddr();
			if (ip.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (Exception e) {
					e.printStackTrace();
				}
				ip = inet.getHostAddress();
			}
		}
		// 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}
}
